package org.wiztools.oembed;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * This implementation uses <code>java.net.HttpURLConnection</code> to open connection
 * to the oEmbed URL.
 * @author subhash
 */
public class OEmbedHttpExecutor extends OEmbedAbstractExecutor {
    
    private static final int HTTP_SUCCESS = 200;
    
    @Override
    public OEmbedResponse get(URL url) throws IOException,
            MalformedURLException, OEmbedException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        
        // Check the response code:
        if(con.getResponseCode() != HTTP_SUCCESS) {
            throw new OEmbedException(con.getResponseCode(),
                    con.getResponseMessage());
        }
        
        final String contentType = con.getHeaderField("Content-type");
        final OEmbedParser parser = getParser(contentType);
        
        Charset charset = ContentTypeUtil.getCharsetFromContentTypeHeader(contentType);
        
        return parser.getResponse(con.getInputStream(), charset);
    }
}
